package com.ruoyi.common.utils.aliyun;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;


public class AliyunSmsUtils {

    /**
     * 发送短信
     *
     * @param phoneNumber 接收短信的手机号码
     * @param templateCode 短信模板ID
     * @param code 验证码
     */
    public static void sendSms(String phoneNumber, String templateCode, String code) {

        String param = "{\"code\":\""+code+"\"}";//验证码
        try {
            Client client = createClient();
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)  //发送的手机号
                    .setSignName("米捷云")   //名字
                    .setTemplateCode(templateCode)  //短信内容编码
                    .setTemplateParam(param);   //验证码
            RuntimeOptions runtime = new RuntimeOptions();
            client.sendSmsWithOptions(request, runtime);

        } catch (TeaException error) {
            System.out.println("Error message: " + error.getMessage());
            System.out.println("Recommend: " + error.getData().get("Recommend"));
        } catch (Exception error) {
            error.printStackTrace();
        }
    }

    /**
     * 创建阿里云短信服务客户端
     *
     * @return Client
     * @throws Exception 创建客户端异常
     */
    private static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId("LTAI4G4AAMSX3hCAdSsQCy5n")
                .setAccessKeySecret("ZzbaY7R9lYUkQFTLYttwDzJWjSNdKW");
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
}
